package com.martin.study;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.core.convert.support.DefaultConversionService;

import java.util.Collections;
import java.util.Set;

public class SpringConverterDemo implements ConditionalGenericConverter {

	public static void main(String[] args) {
		DefaultConversionService conversionService = new DefaultConversionService();
		conversionService.addConverter(new SpringConverterDemo());
		JdkPropertyEditorDemo.User value = conversionService.convert("kong#nan", JdkPropertyEditorDemo.User.class);
		System.out.println(value);
	}

	@Override
	public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
		return sourceType.getType() == String.class && targetType.getType() == JdkPropertyEditorDemo.User.class;
	}

	@Override
	public Set<ConvertiblePair> getConvertibleTypes() {
		return Collections.singleton(new ConvertiblePair(String.class, JdkPropertyEditorDemo.User.class));
	}

	@Override
	public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
		JdkPropertyEditorDemo.User user = new JdkPropertyEditorDemo.User();
		String text = (String) source;
		String[] args = text.split("#");
		user.name = args[0];
		user.gender = args[1];
		return user;
	}
}
